package ptumall.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ptumall.config.AliyunOssConfig;
import ptumall.service.OssService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import java.util.UUID;


@Service
@RequiredArgsConstructor
@Slf4j // 添加日志
public class OssServiceImpl implements OssService {
    private final AliyunOssConfig ossConfig;

    @Override
    public String upload(MultipartFile file) {
        // 处理原始文件名可能为null的情况
        String originalFilename = Optional.ofNullable(file.getOriginalFilename())
                .orElse("file");

        // 安全获取文件后缀
        String extension = "";
        int lastDotIndex = originalFilename.lastIndexOf(".");
        if (lastDotIndex != -1) {
            extension = originalFilename.substring(lastDotIndex);
        }

        // 生成OSS存储路径（保持不变）
        String uploadFileName = "tongueImage/"
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
                + generateUUID()
                + extension;

        OSS ossClient = new OSSClientBuilder()
                .build(ossConfig.getEndPoint(),
                        ossConfig.getAccessKeyId(),
                        ossConfig.getAccessKeySecret());

        try {
            // 上传逻辑（简化判断）
            ossClient.putObject(ossConfig.getBucketName(), uploadFileName, file.getInputStream());
            return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndPoint() + "/" + uploadFileName;
        } catch (Exception e) {
            log.error("OSS文件上传失败: {}", e.getMessage());
            return null;
        } finally {
            ossClient.shutdown();
        }
    }

    private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }
}